import ctypes
import platform

# 加载共享库
print(platform.system())
if platform.system() == "Windows":
  modbus = ctypes.CDLL('./modbus-rtu.dll')
elif platform.system() == "Darwin":
  modbus = ctypes.CDLL('./modbus-rtu.dylib')
else:  # 树莓派
  modbus = ctypes.CDLL('./modbus-rtu.so')

# 定义函数参数类型和返回类型
modbus.ReadRegister.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)]
modbus.ReadRegister.restype = ctypes.c_int

modbus.WriteRegister.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_double]
modbus.WriteRegister.restype = ctypes.c_int

modbus.ReadHoldingRegister.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.POINTER(ctypes.c_double)]
modbus.ReadHoldingRegister.restype = ctypes.c_int

modbus.Connect.argtypes = [ctypes.c_char_p, ctypes.c_int]
modbus.Connect.restype = ctypes.c_int

modbus.Close.argtypes = []
modbus.Close.restype = ctypes.c_int

# 调用ReadRegister函数
modbus.Connect(b'COM2', 9600)

# 写控制寄存器
for i in range(50):
  data = ctypes.c_double()
  result = modbus.WriteRegister(1, 30, b'float', 123.45 + i)
  if result == -3:
    print('Connect error.')
  if result == 0:
    print('Write success.')

# 读控制寄存器 | 读输入寄存器时改成 ReadRegister
for i in range(50):
  data = ctypes.c_double()
  result = modbus.ReadHoldingRegister(1, 30, b'int16', ctypes.byref(data))
  print('Read Result:', result, data.value)
modbus.Close()
